package com.yc.vote.biz;

import com.yc.vote.entity.TpVote;
import com.yc.vote.mapper.TpItemsMapper;
import com.yc.vote.mapper.TpVoteMapper;
import com.yc.vote.util.MBHelper;
import org.apache.ibatis.session.SqlSession;

public class TpVoteBiz {

    public void save(String vname, String vtype, String[]inames)
            throws BizException{
        if(vname==null || vname.trim().isEmpty()){
            throw new BizException("请填写标题");
        }
        if(vtype==null || vtype.trim().isEmpty()){
            throw new BizException("请选择类型");
        }
        if(inames == null || inames.length < 2){
            throw new BizException("选项数必须大于1");
        }

        SqlSession session = MBHelper.openSession(false);
        TpVoteMapper voteMapper = session.getMapper(TpVoteMapper.class);
        TpItemsMapper itemsMapper = session.getMapper(TpItemsMapper.class);
        try{
            // 新增 vote 表记录
            TpVote vote = new TpVote();
            vote.setVname(vname);
            vote.setVtype(vtype);
            voteMapper.insert(vote);
            // 新增 items 表记录 ==> 数组
            for (String iname : inames) {
                itemsMapper.insert(iname, vote.getId());
            }
            session.commit();
        } catch (Exception e){
            session.rollback();
            throw new BizException("业务繁忙,请稍后再试", e);
        } finally {
            session.close();
        }
    }


}
